package tech.wetech.admin3.controller;

import cn.hutool.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.AooAnotherMe;
import tech.wetech.admin3.sys.model.DID;
import tech.wetech.admin3.sys.service.*;
import tech.wetech.admin3.util.CustomResponse;
import tech.wetech.admin3.util.DIDCreateUtil;
import tech.wetech.admin3.util.HashUtil;
import tech.wetech.admin3.util.LianduAPIUtils;

import java.util.*;

@RestController
@RequestMapping("/Digital")
public class AooAnotherMeController {
  private final DIDCreateUtil didCreateUtil;
  private final AooAnotherMeService aooAnotherMeService;
  private final HashUtil hashUtil;
  private final LianduAPIUtils lianduAPIUtil;

  public AooAnotherMeController(
    DIDCreateUtil didCreateUtil,
    AooAnotherMeService aooAnotherMeService,
    HashUtil hashUtil,
    LianduAPIUtils lianduAPIUtil
  ) {
    this.didCreateUtil = didCreateUtil;
    this.aooAnotherMeService = aooAnotherMeService;
    this.hashUtil = hashUtil;
    this.lianduAPIUtil = lianduAPIUtil;
  }

  @PostMapping("/anotherme")
  public ResponseEntity<?> createAnoterMe(
    @RequestParam("owner") String owner,
    @RequestParam("ownerIdNo") String ownerIdNo,
    @RequestParam("email") String email,
    @RequestParam("digitalName") String digitalName,
    @RequestParam("mobile") String mobile,
    @RequestParam("vericode") String vericode,
    @RequestParam(value = "feature", required = false) String feature,
    @RequestParam(value = "purpose", required = false) String purpose,
    @RequestParam(value = "career", required = false) String career,
    @RequestParam(value = "education", required = false) String education,
    @RequestParam(value = "microblog", required = false) String microblog,
    @RequestParam("images") MultipartFile[] images,
    @RequestParam(value = "modelFiles", required = false) MultipartFile[] modelFiles,
    @RequestParam(value = "signFileUrl", required = false) String signFileUrl
  ) {
    try {
      AooAnotherMe anotherMe = aooAnotherMeService.createAnotherMe(owner, ownerIdNo, email, digitalName, mobile, vericode,
        feature, purpose, career, education, microblog, modelFiles, images, signFileUrl);
      return ResponseEntity.ok(new CustomResponse.r1("提交成功", true, anotherMe));
    } catch (AooUserException e) {
      return ResponseEntity.ok(new CustomResponse.r1<>(e.getMessage(), false, null));
    }
  }

  @Transactional
  @PutMapping("/reset/status-anotherme")
  public ResponseEntity<?> resetStatus(
    @RequestParam("uuid") UUID uuid,
    @RequestParam("newStatus") Integer newStatus,
    @RequestParam(value = "checkDesc", required = false) String checkDesc
  ) {
    // 对newStatus的验证
    if (newStatus < 1 || newStatus > 3) {
      return ResponseEntity.badRequest().body(new CustomResponse.r1("状态值无效，只能为0, 1, 2 或3", false, null));
    }
    boolean flag = aooAnotherMeService.resetStatus(uuid, newStatus, checkDesc);

    if (flag) {
      if (newStatus == 2) {
        // 审核通过,创建DID
        AooAnotherMe anotherMe = aooAnotherMeService.findByUuid(uuid);
        String digitalName = anotherMe.getDigitalName();
        String owner = anotherMe.getOwner();
        String imageUrls = anotherMe.getImageUrls();
        String imageHashes = anotherMe.getImageHashes();
        String modelFileUrls = anotherMe.getModelFileUrls();
        String modelFileHashes = anotherMe.getModelFileHashes();

        DID did = didCreateUtil.createDID("z", digitalName, owner, imageUrls, imageHashes, modelFileUrls, modelFileHashes);

        String serial = did.getSerial();
        String didNo = did.getDidNo();
        anotherMe.setSerial(serial);
        anotherMe.setDidNo(didNo);

        String hashV = hashUtil.getStringHash(serial);
        int timeStamp = (int) (System.currentTimeMillis() / 1000);

        Map<String, Object> datainfo = new HashMap<>();
        datainfo.put("name", did.getName());
        datainfo.put("type", did.getType());
        datainfo.put("serial", did.getSerial());
        datainfo.put("didNo", did.getDidNo());
        datainfo.put("ukey", did.getUkey());
        datainfo.put("txhash", did.getTxhash());

//        Gson gson = new Gson();
//        String datainfo_str = gson.toJson(did);

        // 保存到链上
        JSONObject res_saveAuth = lianduAPIUtil.saveAuth(hashV, timeStamp, datainfo.toString()).join();
        System.out.println("res_saveAuth---" + res_saveAuth);

        if ("ok".equals(res_saveAuth.getStr("status"))) {
          did.setTxhash_saveAuth(res_saveAuth.getStr("txhash"));
          System.out.println("上链成功---" + did);
        } else {
          return ResponseEntity.ok(new CustomResponse.r1("did角色已创建，但上链存证失败", true, res_saveAuth.getStr("message")));
        }

        return ResponseEntity.ok(new CustomResponse.r1("审核通过，已创建DID角色", true, did));
      } else if (newStatus == 3) {
        return ResponseEntity.ok(new CustomResponse.r1("审核驳回", true, null));
      } else {
        return ResponseEntity.ok(new CustomResponse.r1("审核中", true, null));
      }
    } else {
      return ResponseEntity.ok(new CustomResponse.r1("未找到该审核资料,请检查id是否正确", false, null));
    }
  }

  @GetMapping("/getall/anotherme")
  public ResponseEntity<?> getAllData(
    @RequestParam("page") int page,
    @RequestParam("size") int size,
    @RequestParam(value = "paid", required = false) Boolean paid
  ) {
    List<?> data;
    if (Boolean.TRUE.equals(paid)) {
      data = aooAnotherMeService.findByPaid(true);
    } else {
      data = aooAnotherMeService.getAllData();
    }

    int total = data.size();
    int start = page * size;
    int end = Math.min(start + size, total);
    List<Object> paginatedList;

    if (start < total) {
      paginatedList = new ArrayList<>(data.subList(start, end));
    } else {
      paginatedList = new ArrayList<>();
    }

    Map<String, Object> result = new HashMap<>();
    result.put("page", page);
    result.put("size", size);
    result.put("total", total);
    result.put("record", paginatedList);

    return ResponseEntity.ok(new CustomResponse.r1("ok", true, result));
  }

  @GetMapping("/getbyemail/anotherme")
  public ResponseEntity<?> getByEmail(
    @RequestParam("email") String email
  ) {
    List data = aooAnotherMeService.findByEmail(email);
    return ResponseEntity.ok(new CustomResponse.r1("ok", true, data));
  }

}
